<template>
	<view>
		<!-- 顶部橙色背景 -->
		<view class="topBackGround"></view>
		<view class="contain">
			<!-- 时间选择器 -->
			<picker mode="date" :value="date" fields="month" @change="bindDateChange" :end="nowDate">
				<view class="pickerDate">
					{{date[0]+date[1]}}
					<image src="../../static/IconArrow.png"></image>
				</view>
			</picker>
			<!-- 数据概览 -->
			<view class="overview">
				<view>
					<view class="overview_title">总支出</view>
					<view>
						<text style="font-size: 28rpx;">￥</text>
						<text>{{billList.spendding.price ? billList.spendding.price : 0}}</text>
					</view>
				</view>
				<view>
					<view class="overview_title">总收入</view>
					<view>
						<text style="font-size: 28rpx;">￥</text>
						<text>{{billList.income.price ? billList.income.price : 0}}</text>
					</view>
				</view>
			</view>
			<!-- 收支明细，这里需要遍历出每一天的账单 -->
			<view style="margin-bottom: 200rpx;">
				<view class="bill_contain" v-for="(items, dayIndex) in billList.bill" :key="dayIndex" v-if="tools.empty(items.bill)">
					<!-- 总收支 -->
					<view class="bill_overview">
						<!-- 日期 -->
						<text>{{tools.sub(items.date)}}</text>
						<!-- 数据 -->
						<text>支 {{items.spendding}}  收 {{items.income}}</text>
					</view>
					<!-- 条目明细 -->
					<view class="bill_item" v-for="(item, itemIndex) in items.bill" :key="itemIndex" @longtap="deleteBillItem(dayIndex, itemIndex, item)" v-if="item != null">
						<view style="display: flex;align-items: center;">
							<image :src="item.costType.icon"></image>
							<view>
								<view v-if="item.spendingType" class="item_name">{{item.spendingType}}-{{item.costType.name}}</view>
								<view v-else class="item_name">{{item.costType.name}}</view>
								<view class="item_tip">{{item.note}}</view> 
							</view>
						</view>
						<view :style="item.price > 0 ? 'color:#FD973F' : 'color:#000'">{{item.price > 0 ? '+'+item.price : item.price}}</view> 
					</view>
				</view>
			</view>
			<!-- 悬浮按钮 -->
			<image class="addBill" src="../../static/addBill.png" @click="showPopup"></image>
			<!-- 账单输入框 -->
			<form v-if="showPop" @submit="submit">
				<!-- 蒙层 -->
				<view class="popup" @click="hidePop"></view>
				<view style="display: flex; justify-content: center;">
					<view class="popup_contain">
						<image src="../../static/cancel.png" @click="hidePop"></image>
						<!-- 收支选择 -->
						<view class="contain_type">
							<view>
								<text :class="selectType == 0 ? 'select_type' : 'normal_type'" style="margin-right: 20rpx;" @click="changeType(0)">支出</text>
								<text :class="selectType == 1 ? 'select_type' : 'normal_type'" @click="changeType(1)">收入</text>
							</view>
							<!-- 记录日期 -->
							<picker mode="date" :value="date" fields="day" @change="changeToDay" :end="nowDate">
								<text class="normal_type">
									{{tools.sub(today)}}
								</text>
							</picker>
						</view>
						<!-- 输入框 -->
						<view class="contain_price">
							<text>￥</text>
							<input type="digit" name="price" />
							<button form-type="submit">确定</button>
						</view>
						<!-- 类型选择 -->
						<view class="income_type">
							<block v-for="(item, index) in typeList" :key="index">
								<view :style="spendingType == item.type ? 'border-bottom: solid 10rpx #FD973F;' : ''" @click="changeSpenddingType(item.type)">{{item.name}}</view>
							</block>
						</view>
						<!-- 成本项目 -->
						<view style="display: flex;flex-wrap: wrap;">
							<view class="type_item" v-for="(item, index) in costList" :key="index" :style="costType == item.type ? 'color: #FD973F' : ''"
							 @click="changeCostType(item.type)">
								<image :src="item.icon"></image>
								<view>{{item.name}}</view>
							</view>
						</view>
						<!-- 添加备注 -->
						<input class="addNote" placeholder="添加备注" placeholder-style="color: #FD973F" name="note"/>
					</view>
				</view>
			</form>
		</view>
	</view>
</template>

<script>
	import dateUtil from '../../util/dateUtil.js';
	import cloudbase from '@cloudbase/js-sdk';
	
	const db = cloudbase.database();
	const dbCmd = db.command;
	let that, _openid,_id;
	export default { 
		data() {
			return {
				date: '',
				today: '',
				nowDate: '',
				showPop: false,
				selectType: 0, // 0 支出	1 收入	
				spendingType: 0, // 0 运营成本	1 管理成本	2 销售成本
				costType: 0, // 代表选中成本中的某一项
				billList: [],	// 获取月账单列表
				typeList: [{
						name: '运营成本',
						type: 0
					},
					{
						name: '管理成本',
						type: 1
					},
					{
						name: '销售成本',
						type: 2
					}
				],
				costList: [{
						name: '培训费',
						type: 0,
						icon: '../../static/training.png'
					},
					{
						name: '乐器采购',
						type: 1,
						icon: '../../static/musical.png'
					},
					{
						name: '其他',
						type: 2,
						icon: '../../static/orther.png'
					}
				],
			}
		},
		onLoad() {
			that = this;
			_openid = getApp().globalData.userInfo._openid; 
			_id = getApp().globalData.userInfo._id; 
			that.date = dateUtil.getFullDate(new Date());
			that.today = dateUtil.getToDay(new Date());
			that.nowDate = dateUtil.toDate(that.today);
			that.getBillList();	
		},
		methods: {
			// 删除一条账单
			deleteBillItem: function(dayIndex, itemIndex, item) {
				let that = this;
				uni.showModal({
					title: '提示',
					content: '确定要删除该账单吗',
					success(res) {
						if(res.confirm) {
							that.deleteDateBaseBill(dayIndex, itemIndex, item);
						}
					}
				})
			},
			// 从数据库删除账单
			deleteDateBaseBill: function(dayIndex, itemIndex, item) {
				let today = this.date;
				// 从数据库删除对应的账单条目，修改支出
				db.collection('user').where({
					_id
				}).update({
					billList: {
						[today[0]]: {
							income: dbCmd.inc(item.billType == 'income' ? -(item.price*100)/100 : 0),
							spendding: dbCmd.inc(item.billType == 'spendding' ? (item.price*100)/100 : 0),
							[today[1]]: {
								income: {
									price: dbCmd.inc(item.billType == 'income' ? -(item.price*100)/100 : 0),
									[item.costType.name]: dbCmd.inc(item.billType == 'income' ? -(item.price*100)/100 : 0)
								},
								spendding: {
									price: dbCmd.inc(item.billType == 'spendding' ? (item.price*100)/100 : 0),
									[item.costType.name]: dbCmd.inc(item.billType == 'spendding' ? (item.price*100)/100 : 0)
								},
								bill: {
									[dayIndex]: {
										bill: {
											[itemIndex]: dbCmd.remove(),
										},
										income: dbCmd.inc(item.billType == 'income' ? -(item.price*100)/100 : 0),
										spendding: dbCmd.inc(item.billType == 'spendding' ? (item.price*100)/100 : 0),
									}
								}
							}
						}
					}
				}).then(res => {
					console.log(res);
					if(res.updated == 1) {
						uni.showToast({
							title: '删除成功',
							icon: 'success',
							duration: 1500
						})
						that.getBillList();
					} 
				})
			},
			// 读取账单
			getBillList: function(){
				// 获取月份
				let date = that.date;
				// 读取该机构的账单
				db.collection('user').where({
					_id
				}).field({"billList": true}).get().then(res=>{
					if(res.data[0].billList){
						that.billList = res.data[0].billList[date[0]][date[1]];
						// console.log(that.billList);
					}
				})
			},
			// 时间选择器
			bindDateChange: function(e) {
				that.date = dateUtil.getFullDate(e.detail.value);
				that.billList = '';
				that.getBillList();
			},
			// 日期选择器
			changeToDay: function(e) {
				that.today = dateUtil.getToDay(new Date(e.detail.value));
			},
			// 显示添加部分
			showPopup: function() {
				that.today = dateUtil.getToDay(new Date());
				that.showPop = true;
			},
			hidePop: function() {
				that.showPop = false;
			},
			// 选中收入支出
			changeType: function(index) {
				that.selectType = index;
				if (index == 0) {
					that.typeList = [{
							name: '运营成本',
							type: 0
						},
						{
							name: '管理成本',
							type: 1
						},
						{
							name: '销售成本',
							type: 2
						}
					]
					that.changeSpenddingType(0);
				} else {
					that.typeList = [];
					that.costList = [{
							name: '乐器收入',
							type: 0,
							icon: '../../static/musical_imcome.png'
						},
						{
							name: '活动收入',
							type: 1,
							icon: '../../static/activity_imcome.png'
						},
						{
							name: '其他收入',
							type: 2,
							icon: '../../static/orther_income.png'
						}
					]
				}
			},
			// 改变成本类型
			changeSpenddingType: function(index) {
				that.spendingType = index;
				switch (index) {
					case 0:
						that.costList = [{
								name: '培训费',
								type: 0,
								icon: '../../static/training.png'
							},
							{
								name: '乐器采购',
								type: 1,
								icon: '../../static/musical.png'
							},
							{
								name: '其他',
								type: 2,
								icon: '../../static/orther.png'
							}
						];
						break;
					case 1:
						that.costList = [{
								name: '财务费用',
								type: 0,
								icon: '../../static/financial.png'
							},
							{
								name: '地租',
								type: 1,
								icon: '../../static/rent.png'
							},
							{
								name: '水电费',
								type: 2,
								icon: '../../static/electricity.png'
							},
							{
								name: '工资发放',
								type: 3,
								icon: '../../static/wage.png'
							},
							{
								name: '其他',
								type: 4,
								icon: '../../static/orther2.png'
							}
						];
						break;
					case 2:
						that.costList = [{
								name: '广告费用',
								type: 0,
								icon: '../../static/advertising.png'
							},
							{
								name: '招生提成',
								type: 1,
								icon: '../../static/commission.png'
							}, {
								name: '活动费用',
								type: 2,
								icon: '../../static/activity.png'
							},
							{
								name: '其他',
								type: 3,
								icon: '../../static/orther3.png'
							}
						];
						break;
				}
				that.costType = 0;
			},
			changeCostType: function(index) {
				that.costType = index;
			},
			// 表单提交
			submit: function(e) {
				let today = this.date;
				let billType = that.selectType == 0 ? 'spendding' : 'income';
				let price = e.detail.value.price;
				if(!price){
					uni.showToast({
						title: '请填写金额',
						icon: 'error',
						duration: 1000
					});
					return;
				}
				let note = e.detail.value.note;
				let spendingType;
				let costType = that.costList[that.costType];
				let flag = false;
				if(billType == 'spendding'){
					spendingType = that.spendingType == 0 ? '运营成本' : that.spendingType == 1 ? '管理成本' : '销售成本';
				}
				// 账单对象
				let billItem = {
					price: billType == 'income' ? (price*100)/100 : ~((price*100)/100-1),
					spendingType,
					costType,
					billType,
					note
				}
				// 获取月账单
				db.collection('user').where({
					_id
				}).field({"billList": true}).get().then(res=>{
					let billList;
					console.log(today);
					if(res.data[0].billList){
						if(res.data[0].billList[today[0]]){
							if(res.data[0].billList[today[0]][today[1]]){
								billList = res.data[0].billList[today[0]][today[1]].bill;
								// console.log(billList); 
								for(let i = 0; i < billList.length; i++){
									if(billList[i].date == that.today){
										// 在这一天追加内容，并退出循环
										billList[i].bill.push(billItem);
										billList[i].spendding += billType == 'spendding' ? (price*100)/100 : 0;
										billList[i].income += billType == 'income' ? (price*100)/100 : 0;
										flag = true;
										break;
									}
								}
							}
						}
					}
					if(flag){
						// 覆盖原来的月账单
						db.collection('user').where({
							_id
						}).update({
							billList: {
								[today[0]]: {
									income: dbCmd.inc(billType == 'income' ? (price*100)/100 : 0),
									spendding: dbCmd.inc(billType == 'spendding' ? (price*100)/100 : 0),
									[today[1]]: {
										income: {
											price: dbCmd.inc(billType == 'income' ? (price*100)/100 : 0),
											[costType.name]: dbCmd.inc(billType == 'income' ? (price*100)/100 : 0)
										},
										spendding: {
											price: dbCmd.inc(billType == 'spendding' ? (price*100)/100 : 0),
											[costType.name]: dbCmd.inc(billType == 'spendding' ? (price*100)/100 : 0)
										},
										bill: billList
									}
								}
							}
						}).then(res=>{
							console.log('修改账单' + _id);
							// console.log((price*100)/100);
							console.log(res);
							if(res.updated != 0){
								uni.showToast({
									title: '已记一笔',
									icon: 'success',
									duration: 1000,
									mask: true
								})
								that.getBillList();
								setTimeout(()=>{
									that.showPop = false;
								}, 1200)
							}
						})
					}else{
						console.log('新增账单' + _id);
						console.log(price);
						// 新增账单
						db.collection('user').where({
							_id
						}).update({
							billList: {
								[today[0]]: {
									date: today[0],
									income: dbCmd.inc(billType == 'income' ? (price*100)/100 : 0),
									spendding: dbCmd.inc(billType == 'spendding' ? (price*100)/100 : 0),
									[today[1]]: {
										date: today[0] + today[1],
										income: {
											price: dbCmd.inc(billType == 'income' ? (price*100)/100 : 0),
											[costType.name]: dbCmd.inc(billType == 'income' ? (price*100)/100 : 0)
										},
										spendding: {
											price: dbCmd.inc(billType == 'spendding' ? (price*100)/100 : 0),
											[costType.name]: dbCmd.inc(billType == 'spendding' ? (price*100)/100 : 0)
										},
										bill: dbCmd.push({
											date: that.today,
											sort: new Date(dateUtil.toDate(that.today)).getTime(),
											income: billType == 'income' ? (price*100)/100 : 0,
											spendding: billType == 'spendding' ? (price*100)/100 : 0,
											bill: [billItem]
										})
									}
								}
							} 
						}).then(res=>{
							console.log(res);
							if(res.updated != 0){
								uni.showToast({
									title: '已记一笔',
									icon: 'success',
									duration: 1000,
									mask: true
								})
								that.getBillList();
								setTimeout(()=>{
									that.showPop = false;
								}, 1200)
								// 对数据内容进行排序
								db.collection('institution').where({
									_openid
								}).update({
									billList: {
										[today[0]]: {
											[today[1]]: {
												bill: dbCmd.push({
													each: [],
													sort: {
														sort: -1
													}
												})
											}
										}
									} 
								})
							}
						})
					}
				})
			}
		}
	}
</script>

<script module="tools" lang="wxs">
	function sub(val) {
		if(!val) return;
		return val.split("年")[1];
	}
	function empty(items) {
		for(var i = 0; i < items.length; i++) {
			if(items[i] != null) {
				return true;
			}
		}
		return false;
	}
	module.exports = {
		sub: sub,
		empty: empty
	}
</script>

<style>
	page {
		background-color: #F3F5F7;
	}

	.topBackGround {
		width: 100%;
		height: 200rpx;
		background-color: #FD973F;
	}

	.contain {
		margin: 10rpx 30rpx;
	}

	.pickerDate {
		font-size: 32rpx;
		color: #fff;
		margin-top: -150rpx;
		margin-left: 20rpx;
		display: flex;
		align-items: center;
	}

	.pickerDate image {
		width: 20rpx;
		height: 15rpx;
		margin-left: 10rpx;
	}

	.overview {
		background-color: #fff;
		padding: 30rpx;
		border-radius: 24rpx;
		margin: 20rpx 0rpx;
		display: flex;
		justify-content: space-around;
		font-size: 36rpx;
	}

	.overview_title {
		font-size: 34rpx;
		color: #666;
		margin-bottom: 20rpx;
	}

	.bill_contain {
		background-color: #fff;
		padding: 30rpx 30rpx 10rpx 30rpx;
		/* height: 300rpx; */
		border-radius: 24rpx;
		margin: 20rpx 0rpx;
	}

	.bill_overview {
		display: flex;
		justify-content: space-between;
		font-size: 28rpx;
		color: #888;
	}

	.bill_item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin: 20rpx 0rpx;
		font-size: 32rpx;
	}

	.bill_item image {
		width: 75rpx;
		height: 75rpx;
		margin-right: 20rpx;
	}

	.item_name {
		font-size: 28rpx;
		color: #444;
	}

	.item_tip {
		font-size: 26rpx;
		color: #999;
	}

	.addBill {
		position: fixed;
		width: 95rpx;
		height: 95rpx;
		right: 60rpx;
		bottom: 120rpx;
	}

	.popup {
		width: 100%;
		height: 100%;
		position: fixed;
		background-color: rgba(0, 0, 0, 0.4);
		top: 0;
		left: 0;
		display: flex;
		justify-content: center;
	}

	.popup_contain {
		position: fixed;
		width: 80%;
		/* height: 80px; */
		top: 18%;
		background-color: #fff;
		border-radius: 24rpx;
		z-index: 999;
		padding: 5%;
	}

	.popup_contain image {
		width: 30rpx;
		height: 30rpx;
	}

	.contain_price {
		display: flex;
		border-bottom: #ddd solid 1rpx;
		padding-bottom: 10rpx;
		margin: 30rpx 0rpx;
		align-items: center;
	}

	.contain_price text {
		font-size: 55rpx;
		font-weight: bold;
		margin-right: 20rpx;
	}

	.contain_price button {
		background-color: #FD973F;
		color: #fff;
		height: 65rpx;
		font-size: 30rpx;
		margin-right: 0rpx;
		align-items: center;
		line-height: 65rpx;
	}

	.contain_type {
		display: flex;
		justify-content: space-between;
		font-size: 30rpx;
		margin-top: 30rpx;
	}

	.contain_type text {
		padding: 10rpx 25rpx;
		border-radius: 40rpx;
	}

	.normal_type {
		background-color: #f1f1f1;
		color: #777;
	}

	.select_type {
		color: #FD973F;
		border: solid 1rpx #FD973F;
		background-color: rgb(253, 151, 63, 0.1);
	}

	.income_type {
		display: flex;
		font-size: 32rpx;
		font-weight: 600;
	}

	.income_type view {
		margin-right: 20rpx;
		padding-bottom: 15rpx;

	}

	.type_item {
		margin-top: 20rpx;
		margin-right: 30rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		font-size: 26rpx;
		color: #888;
	}

	.type_item image {
		width: 75rpx;
		height: 75rpx;
		margin: 10rpx 0rpx;
	}
	
	.addNote{
		font-size: 28rpx;
		color: #FD973F;
		background-color: #FFECDC;
		padding: 10rpx 30rpx;
		border-radius: 40rpx;
		width: 140rpx;
		text-align: center;
		margin-top: 20rpx;
	}
</style>
